package com.rihel.filters;

import com.rihel.dao.UserDAO;
import com.rihel.model.User;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AutoLoginFilter implements Filter {

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        UserDAO userDAO = new UserDAO();
        HttpSession session = request.getSession();
        if(session.getAttribute("user")==null){
            Cookie[] cookies = request.getCookies();
            System.out.println("请求路径为："+request.getRequestURI());
            if(cookies!=null&&cookies.length>0){
                for (Cookie cookie:cookies) {
                    if(cookie.getName().equals("uname")){
                        String uname = cookie.getValue();
                        User user = userDAO.getUserByUname(uname);
                        session.setAttribute("user",user);
                        System.out.println("自动登录成功");
                        break;
                    }
                }
            }
        }
        chain.doFilter(req, resp);

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
